Back to course home
0% completed
Vote For New Content
Google Hard
Shortest Subarray with Sum at Least K (hard)
Solution: Shortest Subarray with Sum at Least K
Reverse Pairs (hard)
Solution: Reverse Pairs
Nth Magical Number (hard)
Solution: Nth Magical Number
Candy (hard)
Solution: Candy
Arithmetic Slices II - Subsequence (hard)
Solution: Arithmetic Slices II - Subsequence
Burst Balloons (hard)
Solution: Burst Balloons
Sum of Distances in Tree (hard)
Solution: Sum of Distances in Tree
Maximum Score of a Good Subarray (hard)
Solution: Maximum Score of a Good Subarray
Trapping Rain Water (hard)
Solution: Trapping Rain Water
First Missing Positive (hard)
Solution: First Missing Positive
Gray Code (medium)
Problem Statement
Given a positive integer n, return any valid n-bit gray code sequence.
An n-bit gray code sequence is a sequence containing integers where:
- Each integer is in the inclusive range [0, 2n - 1].
- Sequence always starts with 0.
- All integers are unique in the sequence.
- The
binary representationofevery pairofadjacent integersdiffersbyexactly one bit. - The
binary representationof thefirstandlastintegersdiffersbyexactly one bit.
Examples
-
Example 1
- Input:
n = 4 - Expected Output:
[0, 1, 3, 2, 6, 7, 5, 4, 12, 13, 15, 14, 10, 11, 9, 8] - Justification: This sequence starts at 0 and each subsequent number differs from the previous one by exactly one bit. The sequence covers all numbers from 0 to 15 (which is 2^4 - 1), adhering to the Gray Code property. It also ensures that the first and last numbers (0 and 8) differ by only one bit.
- Input:
-
Example 2
- Input:
n = 1 - Expected Output:
[0, 1] - Justification: With a single bit, the sequence can only be [0, 1], as both numbers differ by exactly one bit, and the sequence starts with 0.
- Input:
-
Example 3
- Input:
n = 3 - Expected Output:
[0, 1, 3, 2, 6, 7, 5, 4] - Justification: This sequence for 3 bits starts at 0, and each subsequent number differs from the previous by exactly one bit. Additionally, the first and last numbers (0 and 4) differ by only one bit, satisfying all the conditions of Gray Code.
- Input:
Try it yourself
Try solving this question here:
Java
Saved to Cloud
. . . .
Solution: Reverse a LinkedList
Solution: Gray Code
Mark as Completed
On this page
Problem Statement
Examples
Try it yourself